// Package router
// @Author: zhangdi
// @File: permission_check
// @Version: 1.0.0
// @Date: 2023/10/16 16:55
package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"server/application/constant/enums"
	dbsvc2 "server/application/db/system/dbsvc"
	"server/pkg/ginp"
	"server/pkg/utils"
)

// 权限校验
func permissionCheck(c *ginp.ContextPro) {

	//判断该路由是否需要鉴权
	requestApi := c.Request.URL.Path
	for _, router := range Routers {
		currRouterPath := router.Path
		if IsPathMatch(currRouterPath, requestApi) {
			if !router.NeedLogin {
				break //不需要登录，则不需要进行任何权限的校验
			}

			//如果是超级管理员则不需要权限验证,直接允许
			userid := c.GetLoginUserId()
			if userid != 0 && dbsvc2.SysUserIsSuperAdmin(userid) {
				c.Next()
				return
			}

			//开始进行权限判断
			if router.NeedPermission {
				permissionNames := dbsvc2.SysRolePermissionNamesByUserId(userid)
				if !utils.ArrContains(permissionNames, router.PermissionName) {
					errInfo := gin.H{
						"code": enums.RespCodeNoPermission, //禁止访问，无操作权限
						"msg":  fmt.Sprintf("当前账号无权限进行该操作:%s", router.PermissionName),
						"data": nil,
					}
					c.JSON(http.StatusForbidden, errInfo)
					c.Abort()
					return
				}
			}
			break
		} else {
			currRouterPath = ""
		}
	}

	c.Next()
}
